package com.jinzhi.jzweb.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.constants.MessagesEnum;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.IdCardUtils;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzweb.dao.JazSignupGroupDao;
import com.jinzhi.jzweb.dao.JazSignupItemDao;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.param.SignUserQuery;
import com.jinzhi.jzweb.domain.param.UserExamineStatus;
import com.jinzhi.jzweb.domain.vo.JazSignupUserExcelVO;
import com.jinzhi.jzweb.service.JazMessageService;
import com.jinzhi.jzweb.service.JazSignupTeamService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.ExcelUtil;
import com.jinzhi.jzweb.utils.HttpClientUtil;
import com.jinzhi.jzweb.utils.ZipUtils;
import com.jinzhi.sms.support.SmsManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.JazSignupUserDao;
import com.jinzhi.jzweb.service.JazSignupUserService;
import com.jinzhi.common.base.CoreServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * <pre>
 * 报名用户（选手）表
 * </pre>
 * <small> 2024-09-05 15:21:59 | Long</small>
 */
@Service
public class JazSignupUserServiceImpl extends CoreServiceImpl<JazSignupUserDao, JazSignupUserDO> implements JazSignupUserService {

    @Resource
    private JazSignupItemDao jazSignupItemDao;

    @Resource
    private JazSignupGroupDao jazSignupGroupDao;

    @Resource
    private SmsManager smsSerevice;

    @Resource
    private JazSignupTeamService jazSignupTeamService;

    @Resource
    private RedisTemplate<String,Integer> redisTemplate;


    //手机号校验正则
    private static final Pattern PHONE_NUMBER_PATTERN = Pattern.compile("^1(([3][0-9])|([4][014-9])|([5][0-35-9])|([6][2567])|([7][0-8])|([8][0-9])|([9][0-35-9]))[0-9]{8}$");


    public  boolean validatePhoneNumber(String orderPhone) {
        Matcher matcher = PHONE_NUMBER_PATTERN.matcher(orderPhone);
        return matcher.matches();
    }


    /**
     * 分页查询考生报名信息
     *
     * @param signUserQuery
     * @return
     */
    @Override
    public Page<JazSignupUserDO> selectListPage(SignUserQuery signUserQuery) {

        Page<JazSignupUserDO> page = new Page<>(signUserQuery.getCurr(), signUserQuery.getPageSize());

        EntityWrapper<JazSignupUserDO> wrapper = new EntityWrapper<>();
        wrapper.eq(signUserQuery.getGroupId()!=null,"group_id", signUserQuery.getGroupId()); // 组别
        wrapper.like(StringUtil.notEmpty(signUserQuery.getName()),"name", signUserQuery.getName()); // 姓名
        wrapper.eq(signUserQuery.getItemId()!=null,"item_id", signUserQuery.getItemId()); // 项目
        wrapper.like(StringUtil.notEmpty(signUserQuery.getTeamName()),"team_name", signUserQuery.getTeamName()); // 队伍
        // 查询状态
        if (signUserQuery.getStatus()!=null){
            if (signUserQuery.getStatus()==1){
                wrapper.eq("status", signUserQuery.getStatus());
            }else if (signUserQuery.getStatus()==2){
                wrapper.in("status", Arrays.asList(2,4));
            }
        }
        // 审核结果
        wrapper.eq(signUserQuery.getResult()!=null,"result", signUserQuery.getResult());
        wrapper.orderBy("update_time",false);
        // 查询
        Page<JazSignupUserDO> userDOPage = this.selectPage(page, wrapper);

        // 组装数据
        userDOPage.getRecords().forEach(item -> {
            extractedName(item);
        });

        return userDOPage;
    }

    /**
     * 封装 组别名称、参赛名称、队伍名称
     * @param item
     */
    private void extractedName(JazSignupUserDO item) {
        // 查询组别名称
        JazSignupGroupDO jazSignupGroupDO = jazSignupGroupDao.selectById(item.getGroupId());
        if (jazSignupGroupDO != null){
            item.setGroupName(jazSignupGroupDO.getName());
        }
        // 查询参赛名称
        JazSignupItemDO jazSignupItemDO = jazSignupItemDao.selectById(item.getItemId());
        if (jazSignupItemDO != null){
            item.setItemName(jazSignupItemDO.getName());
        }
        // 查询所属队伍
//        JazSignupTeamDO jazSignupTeamDO = jazSignupTeamService.selectById(item.getTeamId());
//        if (jazSignupTeamDO != null){
//            item.setTeamName(jazSignupTeamDO.getName());
//        }
    }


    /**
     * 根据id进行查询
     *
     * @param id
     * @return
     */
    @Override
    public JazSignupUserDO getById(Long id) {

        JazSignupUserDO jazSignupUserDO = this.selectById(id);
        if (jazSignupUserDO == null){
            return null;
        }
        // 组装数据
        // 查询组别名称
        extractedName(jazSignupUserDO);

        return jazSignupUserDO;
    }


    /**
     * 修改审核状态
     *
     * @param jazSignupUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> updateStatusById(JazSignupUserDO jazSignupUser) {
        JazSignupUserDO jazSignupUserDO = this.selectById(jazSignupUser.getId());
        if (jazSignupUserDO == null){
            return Result.fail();
        }
        // 获取队伍信息
        JazSignupTeamDO jazSignupTeamDO = jazSignupTeamService.selectById(jazSignupUserDO.getTeamId());
        if (jazSignupTeamDO == null){
            return Result.fail();
        }

        // 获取审核状态
        if (jazSignupUser.getResult()==1){ // 通过
            jazSignupUserDO.setResult(jazSignupUser.getResult());
            jazSignupUserDO.setStatus(2);
            jazSignupUserDO.setReviewTime(new Date()); // 审核时间
        }else if (jazSignupUser.getResult()==2){ // 不通过
            jazSignupUserDO.setResult(jazSignupUser.getResult());
            jazSignupUserDO.setStatus(2);
            jazSignupUserDO.setRefuseReasion(jazSignupUser.getRefuseReasion());
            jazSignupUserDO.setReviewTime(new Date()); // 审核时间
            // 获取历史审核时间
            if (StringUtil.notEmpty(jazSignupUserDO.getHistoryReview())){ // 已审过，且没通过
                List<UserExamineStatus> userExamineStatuses = JSON.parseArray(jazSignupUserDO.getHistoryReview(), UserExamineStatus.class);
                UserExamineStatus userExamineStatus = new UserExamineStatus();
                userExamineStatus.setStatus(jazSignupUserDO.getStatus()); // 审核状态
                userExamineStatus.setResult(jazSignupUserDO.getResult()); // 审核结果
                userExamineStatus.setReviewTime(jazSignupUserDO.getReviewTime()); // 审核时间
                userExamineStatus.setRefuseReasion(jazSignupUserDO.getRefuseReasion()); // 拒绝原因
                userExamineStatuses.add(userExamineStatus);
                // 转为JSON存储
                String jsonString = JSON.toJSONString(userExamineStatuses);
                jazSignupUserDO.setHistoryReview(jsonString);
            }else { // 第一次审核且为拒绝
                List<UserExamineStatus> userExamineStatuses=new ArrayList<>();
                UserExamineStatus userExamineStatus = new UserExamineStatus();
                userExamineStatus.setStatus(jazSignupUserDO.getStatus()); // 审核状态
                userExamineStatus.setResult(jazSignupUserDO.getResult()); // 审核结果
                userExamineStatus.setReviewTime(jazSignupUserDO.getReviewTime()); // 审核时间
                userExamineStatus.setRefuseReasion(jazSignupUserDO.getRefuseReasion()); // 拒绝原因
                userExamineStatuses.add(userExamineStatus);
                // 转为JSON存储
                String jsonString = JSON.toJSONString(userExamineStatuses);
                jazSignupUserDO.setHistoryReview(jsonString);
            }
            jazSignupUserDO.setStatus(4);
        }

        // 更新选手
        boolean b = this.updateById(jazSignupUserDO);

        // 判断队伍下是否有审核通过的数据
        List<JazSignupUserDO> list = this.selectList(new EntityWrapper<JazSignupUserDO>().eq("team_id", jazSignupUserDO.getTeamId())
                .eq("result", 1));
        if (list.size()>0){
            if (jazSignupUser.getResult()==1) { // 通过
                // 设置队伍审核结果
                jazSignupTeamDO.setResult(1); // 已通过
            }else if (jazSignupUser.getResult()==2) { // 不通过
                // 设置队伍审核结果
                jazSignupTeamDO.setResult(2); // 未通过
            }
        }

        // 更新队伍信息
        boolean b1 = jazSignupTeamService.updateById(jazSignupTeamDO);

        // 发送短信
        Map map = new HashMap();
        map.put("name",jazSignupUserDO.getName());
        // redis-key
        String key="jinzhi:sign:" + jazSignupUserDO.getPhone();
        // 发送审核通过的短信
        Integer i = redisTemplate.opsForValue().get(key);
        if (i==null || i<=0){
            if(jazSignupUserDO.getResult()==1){ // 审核通过
                smsSerevice.send(jazSignupUserDO.getPhone(), MessagesEnum.MESSAGE_220.getCode(),map);
            }else if (jazSignupUserDO.getResult()==2){ // 审核未通过
                smsSerevice.send(jazSignupUserDO.getPhone(), MessagesEnum.MESSAGE_221.getCode(),map);
            }
            redisTemplate.opsForValue().set(key,1,1, TimeUnit.DAYS);
            log.warn("短信发送成功，手机号存在于缓存中，手机号：{}",jazSignupUserDO.getPhone());
        }else if (i>0&&i<20){
            if(jazSignupUserDO.getResult()==1){ // 审核通过
                smsSerevice.send(jazSignupUserDO.getPhone(), MessagesEnum.MESSAGE_220.getCode(),map);
            }else if (jazSignupUserDO.getResult()==2){ // 审核未通过
                smsSerevice.send(jazSignupUserDO.getPhone(), MessagesEnum.MESSAGE_221.getCode(),map);
            }
            redisTemplate.opsForValue().set(key,i+1,1, TimeUnit.DAYS);
            log.warn("短信发送成功，手机号存在于缓存中，手机号：{}",jazSignupUserDO.getPhone());
        }else {
            log.warn("短信发送失败，手机号存在于缓存中，手机号：{}",jazSignupUserDO.getPhone());
            return Result.fail("短信发送失败,今日已达上限，请明日再试");
        }

        return b?Result.ok():Result.fail();
    }


    /**
     * 修改选手信息
     *
     * @param jazSignupUser
     * @return
     */
    @Override
    public Result<String> updateSignupUserById(JazSignupUserDO jazSignupUser) {
        if (jazSignupUser==null){
            return Result.fail("参数错误");
        }


        // 校验身份证号
        if(StringUtil.notEmpty(jazSignupUser.getIdentityCard())){
            if (!IdCardUtils.isIdcard(jazSignupUser.getIdentityCard())) {
                return Result.fail("身份证号码不正确，请输入正确的身份证号");
            }
        }

        //校验手机号
        if(StringUtil.notEmpty(jazSignupUser.getPhone())){
            if (!validatePhoneNumber(jazSignupUser.getPhone())) {
                return Result.fail("电话号码格式错误");
            }
        }


        // 获取选手详细信息
        JazSignupUserDO jazSignupUserDO = this.selectById(jazSignupUser.getId());
        // 获取当前队伍下的所有选手信息
        List<JazSignupUserDO> list = this.selectList(new EntityWrapper<JazSignupUserDO>()
                .eq("team_id", jazSignupUserDO.getTeamId())
                .eq("group_id", jazSignupUserDO.getGroupId()).eq("type", 2));

        // 判断选手的类型
        if (jazSignupUser.getType()==1){ // 领队
             // 判断是否修改了组别 或 队伍信息
            if (jazSignupUser.getGroupId()!=null && !jazSignupUser.getGroupId().equals(jazSignupUserDO.getGroupId()) ||
                    StringUtil.notEmpty(jazSignupUser.getTeamName()) && !jazSignupUser.getTeamName().equals(jazSignupUserDO.getTeamName())){
                // 先查询队伍是否存在
                JazSignupTeamDO jazSignupTeamDO = jazSignupTeamService.selectOne(new EntityWrapper<JazSignupTeamDO>()
                        .eq("id", jazSignupUserDO.getTeamId())
                        .eq("group_id", jazSignupUser.getGroupId()));
                if (jazSignupTeamDO==null){
                    // 为空创建队伍信息
                    jazSignupTeamDO = new JazSignupTeamDO();
                    jazSignupTeamDO.setGroupId(jazSignupUser.getGroupId());
                    jazSignupTeamDO.setName(jazSignupUser.getTeamName());
                    jazSignupTeamDO.setCreateTime(jazSignupUserDO.getCreateTime());
                    jazSignupTeamService.insert(jazSignupTeamDO);
                    jazSignupUser.setTeamId(jazSignupTeamDO.getId());
                    // 领队更换了队伍信息，将原有队伍信息清空
                    for (JazSignupUserDO userDO : list) {
                        userDO.setTeamId(null);
                        userDO.setTeamName(null);
                        this.updateById(userDO);
                    }
                }else {
                    // 不为空，修改队伍信息名称
                    for (JazSignupUserDO userDO1 : list) {
                        userDO1.setTeamId(jazSignupTeamDO.getId());
                        userDO1.setTeamName(jazSignupUser.getTeamName());
                        this.updateById(userDO1);
                    }
                    // 更改队伍信息
                    jazSignupTeamDO.setName(jazSignupUser.getTeamName());
                    jazSignupTeamService.updateById(jazSignupTeamDO);

                }
            }
            //
            jazSignupUser.setTeamId(jazSignupUserDO.getTeamId());

            if (StringUtil.notEmpty(jazSignupUserDO.getRefuseReasion())){
                jazSignupUser.setRefuseReasion(jazSignupUserDO.getRefuseReasion());
            }
            // 更新报名信息
            boolean b = this.updateById(jazSignupUser);
            return b?Result.ok():Result.fail();

        } else if (jazSignupUser.getType()==2) { // 选手信息

            // 判断是否修改了组别 或 队伍信息
            if (jazSignupUser.getGroupId()!=null && !jazSignupUser.getGroupId().equals(jazSignupUserDO.getGroupId()) ||
                    !jazSignupUser.getTeamId().equals(jazSignupUserDO.getTeamId()))
            {
                // 先查询队伍是否存在
                JazSignupTeamDO jazSignupTeamDO = jazSignupTeamService.selectOne(new EntityWrapper<JazSignupTeamDO>()
                        .eq("id", jazSignupUser.getTeamId())
                        .eq("group_id", jazSignupUser.getGroupId()));
                if (jazSignupTeamDO==null){
                    // 为空创建队伍信息
                    jazSignupTeamDO = new JazSignupTeamDO();
                    jazSignupTeamDO.setGroupId(jazSignupUser.getGroupId());
                    jazSignupTeamDO.setName(jazSignupUser.getTeamName());
                    jazSignupTeamDO.setCreateTime(jazSignupUserDO.getCreateTime());
                    jazSignupTeamService.insert(jazSignupTeamDO);
                    jazSignupUser.setTeamId(jazSignupTeamDO.getId());
                }else {
                    // 判断是否已存在领队信息
                    JazSignupUserDO userDO = this.selectOne(new EntityWrapper<JazSignupUserDO>().eq("group_id", jazSignupUser.getGroupId())
                            .eq("team_id", jazSignupUser.getTeamId()).eq("type", 1));
                    if (userDO==null){
                        return Result.fail("该队伍还未有领队报名，请先报名领队信息");
                    }
                    // 不为空
                    jazSignupUser.setTeamId(jazSignupTeamDO.getId());
                }
            }
            JazSignupTeamDO jazSignupTeamDO = jazSignupTeamService.selectById(jazSignupUser.getTeamId());
            if (jazSignupTeamDO!=null){
                jazSignupUser.setTeamName(jazSignupTeamDO.getName());
            }

            if (StringUtil.notEmpty(jazSignupUserDO.getRefuseReasion())){
                jazSignupUser.setRefuseReasion(jazSignupUserDO.getRefuseReasion());
            }

            // 更新报名信息
            boolean b = this.updateById(jazSignupUser);
            return b?Result.ok():Result.fail();

        }

        return null;
    }

    /**
     * 导出
     *
     * @param response
     * @param signUserQuery
     */
    @Override
    public void downloadImportTemplate(HttpServletResponse response, SignUserQuery signUserQuery) {
        Map<String,byte[]> fileBufMap=new HashMap<>();

        // 判断是否传入要导出的数据id，如果没有，则导出全部
        if (signUserQuery.getIds().length>1){// 根据id进行导出 压缩包
            List<JazSignupUserExcelVO> list = new ArrayList<>();
            // 查询传入的id数据
            List<JazSignupUserDO> signupUserDOList = this.selectList(new EntityWrapper<JazSignupUserDO>()
                    .in("id", signUserQuery.getIds()));

            // 导出压缩包
            exportZip(response, signupUserDOList, list, fileBufMap);
        } else if (signUserQuery.getIds().length==1) {
            // 导出单个文件
            exportOne(response, signUserQuery);
        } else {
            List<JazSignupUserExcelVO> list = new ArrayList<>();
            // 导出全部数据 压缩包
            List<JazSignupUserDO> jazSignupUserDOSList = this.selectList(null);
            // 导出压缩包
            exportZip(response, jazSignupUserDOSList, list, fileBufMap);
        }
    }

    /**
     * 导出要所报
     * @param response
     * @param jazSignupUserDOSList
     * @param list
     * @param fileBufMap
     */
    private void exportZip(HttpServletResponse response, List<JazSignupUserDO> jazSignupUserDOSList, List<JazSignupUserExcelVO> list, Map<String, byte[]> fileBufMap) {
        //遍历报名信息
        for (JazSignupUserDO jazSignupUserDO : jazSignupUserDOSList) {
            JazSignupUserExcelVO jazSignupUserExcelVO = new JazSignupUserExcelVO();
            BeanUtils.copyProperties(jazSignupUserDO,jazSignupUserExcelVO);
            // 数据转换
            if (jazSignupUserDO.getType()==1){
                jazSignupUserExcelVO.setType("领队");
            }else if (jazSignupUserDO.getType()==2){
                jazSignupUserExcelVO.setType("参赛选手");
            }
            // 性别转换
            if (jazSignupUserDO.getSex()==1){
                jazSignupUserExcelVO.setSex("男");
            }else if (jazSignupUserDO.getSex()==2){
                jazSignupUserExcelVO.setSex("女");
            }else {
                jazSignupUserExcelVO.setSex("未知");
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            jazSignupUserExcelVO.setCreateTime(simpleDateFormat.format(jazSignupUserDO.getCreateTime()));
            // 查询组别名称
            JazSignupGroupDO jazSignupGroupDO = jazSignupGroupDao.selectById(jazSignupUserDO.getGroupId());
            if (jazSignupGroupDO != null){
                jazSignupUserExcelVO.setGroupName(jazSignupGroupDO.getName());
            }
            // 查询参赛名称
            JazSignupItemDO jazSignupItemDO = jazSignupItemDao.selectById(jazSignupUserDO.getItemId());
            if (jazSignupItemDO != null){
                jazSignupUserExcelVO.setItemName(jazSignupItemDO.getName());
            }

            // 处理个人图片
            if (StringUtil.notEmpty(jazSignupUserDO.getUserImg())){
                String[] split2 = jazSignupUserDO.getUserImg().split(",");
                List<byte[]> userImg=new ArrayList<>();
                for (String s : split2) {
                    userImg.add(HttpClientUtil.getImageFromNetByUrl(s));
                }
                jazSignupUserExcelVO.setUserImg(mergeImages(userImg));
            }
            // 处理身份证图片
            if (StringUtil.notEmpty(jazSignupUserDO.getIdentityCardImg())){
                String[] split1 = jazSignupUserDO.getIdentityCardImg().split(",");
                List<byte[]> cardImg=new ArrayList<>();
                for (String s : split1) {
                    cardImg.add(HttpClientUtil.getImageFromNetByUrl(s));
                }
                jazSignupUserExcelVO.setIdentityCardImg(mergeImages(cardImg));
            }
            // 其他图片
            if (StringUtil.notEmpty(jazSignupUserDO.getOther())){
                String[] split = jazSignupUserDO.getOther().split(",");
                List<byte[]> other=new ArrayList<>();
                for (String s : split) {
                    other.add(HttpClientUtil.getImageFromNetByUrl(s));
                }
                jazSignupUserExcelVO.setOther(mergeImages(other));
            }

            // 处理报名表格
            //jazSignupUserExcelVO.setApplyForm(HttpClientUtil.getImageFromNetByUrl(jazSignupUserDO.getApplyForm()));

            // 添加到集合
            list.add(jazSignupUserExcelVO);

            // 设置文件名和标题
            String fileName = jazSignupUserExcelVO.getGroupName()+"-"+jazSignupUserDO.getName()+"-"+jazSignupUserDO.getPhone()+".xls";
            String title = jazSignupUserExcelVO.getGroupName()+"-"+jazSignupUserExcelVO.getName()+"-"+jazSignupUserDO.getPhone();

            //导出操作 1
            byte[] exportAccountExcelBytes = new byte[0];
            try {
                exportAccountExcelBytes = ExcelUtil.getExportExcelBytes(list, title, title, JazSignupUserExcelVO.class, fileName, response);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // 将文件名放入map的key中，字节文件内容放入value中
            fileBufMap.put(fileName,exportAccountExcelBytes);

        }
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        String fileName = null;
        try {
            fileName =  URLEncoder.encode("报名信息.zip", "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,  "attachment; filename*=" + fileName);
        try {
            // 压缩包导出
            ZipUtils.downloadZipForByteMore(response.getOutputStream(), fileBufMap);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 单个文件导出
     * @param response
     * @param signUserQuery
     */
    private void exportOne(HttpServletResponse response, SignUserQuery signUserQuery) {
        List<JazSignupUserExcelVO> list = new ArrayList<>();
        // 单个导出
        JazSignupUserDO jazSignupUserDO = this.selectById(signUserQuery.getIds()[0]);
        if (jazSignupUserDO==null){
            return;
        }
        JazSignupUserExcelVO jazSignupUserExcelVO = new JazSignupUserExcelVO();
        BeanUtils.copyProperties(jazSignupUserDO,jazSignupUserExcelVO);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        jazSignupUserExcelVO.setCreateTime(simpleDateFormat.format(jazSignupUserDO.getCreateTime()));
        // 数据转换
        if (jazSignupUserDO.getType()==1){
            jazSignupUserExcelVO.setType("领队");
        }else if (jazSignupUserDO.getType()==2){
            jazSignupUserExcelVO.setType("参赛选手");
        }
        // 性别转换
        if (jazSignupUserDO.getSex()==1){
            jazSignupUserExcelVO.setSex("男");
        }else if (jazSignupUserDO.getSex()==2){
            jazSignupUserExcelVO.setSex("女");
        }else {
            jazSignupUserExcelVO.setSex("未知");
        }
        // 查询组别名称
        JazSignupGroupDO jazSignupGroupDO = jazSignupGroupDao.selectById(jazSignupUserDO.getGroupId());
        if (jazSignupGroupDO != null){
            jazSignupUserExcelVO.setGroupName(jazSignupGroupDO.getName());
        }
        // 查询参赛名称
        JazSignupItemDO jazSignupItemDO = jazSignupItemDao.selectById(jazSignupUserDO.getItemId());
        if (jazSignupItemDO != null){
            jazSignupUserExcelVO.setItemName(jazSignupItemDO.getName());
        }
        // 处理个人图片
//        byte[] imageFromNetByUrl = HttpClientUtil.getImageFromNetByUrl(jazSignupUserDO.getUserImg());
//        jazSignupUserExcelVO.setUserImg(imageFromNetByUrl);
//        // 处理身份证图片
//        byte[] imageFromNetByUrl1 = HttpClientUtil.getImageFromNetByUrl(jazSignupUserDO.getIdentityCardImg());
//        jazSignupUserExcelVO.setIdentityCardImg(imageFromNetByUrl1);
        if (StringUtil.notEmpty(jazSignupUserDO.getUserImg())){
            String[] split2 = jazSignupUserDO.getUserImg().split(",");
            List<byte[]> userImg=new ArrayList<>();
            for (String s : split2) {
                userImg.add(HttpClientUtil.getImageFromNetByUrl(s));
            }
            jazSignupUserExcelVO.setUserImg(mergeImages(userImg));
        }
        // 处理身份证图片
        if (StringUtil.notEmpty(jazSignupUserDO.getIdentityCardImg())){
            String[] split1 = jazSignupUserDO.getIdentityCardImg().split(",");
            List<byte[]> cardImg=new ArrayList<>();
            for (String s : split1) {
                cardImg.add(HttpClientUtil.getImageFromNetByUrl(s));
            }
            jazSignupUserExcelVO.setIdentityCardImg(mergeImages(cardImg));
        }
        // 其他图片
        if (StringUtil.notEmpty(jazSignupUserDO.getOther())){
            String[] split = jazSignupUserDO.getOther().split(",");
            List<byte[]> other=new ArrayList<>();
            for (String s : split) {
                other.add(HttpClientUtil.getImageFromNetByUrl(s));
            }
            jazSignupUserExcelVO.setOther(mergeImages(other));
        }
        // 处理报名表格
        //jazSignupUserExcelVO.setApplyForm(HttpClientUtil.getImageFromNetByUrl(jazSignupUserDO.getApplyForm()));

        // 添加到数组
        list.add(jazSignupUserExcelVO);
        // 文件名
        String title=jazSignupUserExcelVO.getGroupName()+"-"+jazSignupUserExcelVO.getName()+"-"+jazSignupUserExcelVO.getPhone();

        //导出操作
        EasyPoiUtil.exportExcel(list,title ,
                title,
                JazSignupUserExcelVO.class,
                title, response);
    }




    // 合并图片的方法
    // 合并图片的方法
    private static byte[] mergeImages(List<byte[]> imagePaths) {
        // 计算合并后的图片大小
        int totalWidth = 0;
        int maxHeight = 0;
        BufferedImage[] images = new BufferedImage[imagePaths.size()];
        for (int i = 0; i < imagePaths.size(); i++) {
            ByteArrayInputStream bis = new ByteArrayInputStream(imagePaths.get(i));
            BufferedImage image = null;
            try {
                image = ImageIO.read(bis);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            totalWidth += image.getWidth();
            maxHeight = Math.max(maxHeight, image.getHeight());
            images[i] = image;
        }

        // 创建一个空白画布，用于绘制合并后的图片
        BufferedImage mergedImage = new BufferedImage(totalWidth, maxHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = mergedImage.createGraphics();
        int x = 0;
        for (BufferedImage image : images) {
            g2d.drawImage(image, x, 0, null);
            x += image.getWidth();
        }
        g2d.dispose();

        // 将合并后的图片转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(mergedImage, "png", baos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return baos.toByteArray();
    }





}
